<template>
  <header class="header">
    <div class="search-container">
      <input
        type="text"
        v-model="searchInput"
        placeholder="搜索商品"
        @input="debouncedHandleSearch"
        ref="searchInputRef"
      />
      <button v-if="searchInput" class="clear-button" @click="clearSearch">
        &times;
      </button>
    </div>
  </header>
</template>

<script setup>
import { ref, defineEmits } from 'vue'
import _ from 'lodash' // 使用 lodash 进行防抖处理

const searchInput = ref('')
const emit = defineEmits(['search'])
const searchInputRef = ref(null)

// 防抖处理搜索事件
const debouncedHandleSearch = _.debounce(() => {
  handleSearch()
}, 300)

const handleSearch = () => {
  emit('search', searchInput.value)
}

const clearSearch = () => {
  searchInput.value = ''
  searchInputRef.value.focus() // 聚焦到输入框
  handleSearch()
}
</script>

<style scoped>
.header {
  background-color: #fff;
  padding: 10px 20px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: center;
}

.search-container {
  position: relative;
  width: 100%;
  max-width: 600px;
}

input[type="text"] {
  width: 100%;
  padding: 10px 35px 10px 15px; /* 留出空间给清除按钮 */
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 20px;
  outline: none;
  transition: border-color 0.3s ease;
}

input[type="text"]:focus {
  border-color: #007bff;
}

.clear-button {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  font-size: 18px;
  color: #999;
  cursor: pointer;
  outline: none;
}

.clear-button:hover {
  color: #666;
}
</style>
